using System;
using System.IO;
using System.Xml.Serialization;

namespace TVListings
{
	public class UserSettings
	{
		ProgramDisplay.ColorMapping[] colors;
		string dataFile;
		string updateCommand;
		string leadCommand;
		string lagCommand;
		decimal commandLeadTime;
		decimal commandLagTime;
		decimal notificationLead;

		public UserSettings()
		{
			dataFile = "tv_grab_na_dd.xmltv";
			updateCommand = "tv_grab_na_dd --output=";
			leadCommand = "ffmpeg record";
			lagCommand = "ffmpeg transcode";
			commandLeadTime = 1.0M;
			commandLagTime = 1.0M;
			notificationLead = 5.0M;
			colors = new ProgramDisplay.ColorMapping[0];
		}

		public string DataFile
		{
			get { return dataFile; }
			set { dataFile = value; Dirty = true; }
		}

		public string UpdateCommand
		{
			get { return updateCommand; }
			set { updateCommand = value; Dirty = true; }
		}

		public string LeadCommand
		{
			get { return leadCommand; }
			set { leadCommand = value; Dirty = true; }
		}

		public decimal CommandLeadTime
		{
			get { return commandLeadTime; }
			set { commandLeadTime = value; Dirty = true; }
		}

		public string LagCommand
		{
			get { return lagCommand; }
			set { lagCommand = value; Dirty = true; }
		}

		public decimal CommandLagTime
		{
			get { return commandLagTime; }
			set { commandLagTime = value; Dirty = true; }
		}

		public decimal NotificationLead
		{
			get { return notificationLead; }
			set { notificationLead = value; Dirty = true; }
		}
		
		public ProgramDisplay.ColorMapping[] Colors
		{
			get { return colors; }
			set { colors = value; Dirty = true; }
		}

		#region Helper functions
		[XmlIgnore]
		private bool Dirty = false;
		static string Filename;
		public static string SettingsPath;
		static UserSettings Singleton;
		static UserSettings()
		{
			string Executable = Environment.CommandLine;
			if (Executable.StartsWith("\"") && Executable.EndsWith("\""))
				Executable = Executable.Substring(1, Executable.Length - 2);
			SettingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
				Path.GetFileNameWithoutExtension(Executable));
			Filename = Path.Combine(SettingsPath, "Settings.xml");

			if (File.Exists(Filename))
			{
				XmlSerializer serializer = new XmlSerializer(typeof(UserSettings));
				StreamReader file = File.OpenText(Filename);
				Singleton = (UserSettings)serializer.Deserialize(file);
			}
			else
				Singleton = new UserSettings();
		}

		public static UserSettings GetSettings()
		{
			return Singleton;
		}

		public void Save()
		{
			if (Dirty)
			{
				XmlSerializer serializer = new XmlSerializer(typeof(UserSettings));
				StreamWriter file = File.CreateText(Filename);
				serializer.Serialize(file, this);
				file.Close();
				Dirty = false;
			}
		}
		#endregion
	}
}